package com.sgb.knowledgeshare.view.fragment;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentShareVideoplayListBinding;
import com.sgb.knowledgeshare.view.adapter.RecommendAdapter;
import com.sgb.knowledgeshare.viewmodel.ShareVideoPlayListModel;
import com.sgb.knowledgeshare.weight.ControllerView;
import com.sgb.knowledgeshare.weight.FullScreenVideoView2;
import com.sgb.knowledgeshare.weight.ViewPagerLayoutManager;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.base.di.AppComponent;
import java.io.Serializable;
import java.util.List;

/**
 * Created by fq on 2020/9/11 0011
 * Description：分享模块点击单个视频跳转的视频播放
 */
public class ShareVideoPlayListFragment extends AppLazyFragment {

    private static String VIDEOPLAYTYPE = "videoplay_type";
    private static String VIDEOUSERLIST = "VideoUserListEntity";
    private static String POS = "pos";

    ShareVideoPlayListModel viewModel;
    private FragmentShareVideoplayListBinding binding;
    private RecommendAdapter recommendAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private List<VideoBean> bean;
    private int page = 1;
    private FullScreenVideoView2 videoView;
    private ViewPagerLayoutManager viewPagerLayoutManager;
    private ControllerView controllerView;
    private ImageView ivPlay;
    private ImageView ivCurCover;
    private String videoplaytype;
    private int anInt;
    private ImageView ivCover;
    private boolean isLoadMore;
    private int thisPosition;
    private ImageView mThumbImageBg;

    public static ShareVideoPlayListFragment newInstance(String type, int pos, List<VideoBean> bean) {
        ShareVideoPlayListFragment fragment = new ShareVideoPlayListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(VIDEOPLAYTYPE, type);
        bundle.putInt(POS, pos);
        bundle.putSerializable(VIDEOUSERLIST, (Serializable) bean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_share_videoplay_list, container, false);
        viewModel = new ViewModelProvider(this).get(ShareVideoPlayListModel.class);
        viewModel.setActivity(ShareVideoPlayListFragment.this);
        if (getArguments() != null) {
            videoplaytype = getArguments().getString(VIDEOPLAYTYPE);
            anInt = getArguments().getInt(POS) + 1;
            bean = (List<VideoBean>) getArguments().getSerializable(VIDEOUSERLIST);
        }
        binding.backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initData();
    }

    private void initData() {
        if (bean == null) {
            viewModel.getVideoTypeList(page, videoplaytype);
        }
    }
/*
    @Override
    public void onVisible() {
        super.onVisible();
       *//* if (ivPlay != null) {
            ivPlay.setVisibility(View.GONE);
        }*//*
        if (videoView != null) {
          *//*  ivCover.setVisibility(View.GONE);
            videoView.setVisibility(View.VISIBLE);*//*
            videoView.start();
        }
    }

    @Override
    public void onInvisible() {
        super.onInvisible();
        if (videoView != null) {
            videoView.pause();
           // videoView.setVisibility(View.GONE);
            //ivCover.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (videoView != null) {
            videoView.pause();
            //videoView.setVisibility(View.GONE);
           // ivCover.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        if (videoView != null) {
            videoView.stopPlayback();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        videoView = null;
    }

    @Override
    protected void initView() {
        if (bean != null) {
            for (VideoBean at : bean) {
                if (at.getIsLaud() == 0) {// 是否点赞（0：不是，1：是）
                    at.setLiked(false);
                } else {
                    at.setLiked(true);
                }
            }
            Collections.swap(bean,getArguments().getInt(POS),0);
        }
        videoView = new FullScreenVideoView2(getContext());
        setViewPagerLayoutManager();
        recommendAdapter = new RecommendAdapter2(getActivity(), bean, new RecommendAdapter2.CallBack() {
            @Override
            public void onCallBack(ItemViewHolder holder) {
                updateVideo(holder.getAdapterPosition() - 1);
            }
        });
     //   recommendAdapter.setUpdateCurIndex(anInt,bean);
        recommendAdapter.setClickListener(new RecommendAdapter2.ClickListener() {
            @Override
            public void ClickListenerclick(String VideoId) {
                viewModel.setLike(VideoId + "");
                setShuangJiDianZan(VideoId);
            }
        });
        LRecyclerViewAdapter mLRecyclerViewAdapter = new LRecyclerViewAdapter(recommendAdapter);
        binding.lrecyclerview.setAdapter(mLRecyclerViewAdapter);
        binding.lrecyclerview.setPullRefreshEnabled(true);
        binding.lrecyclerview.setLoadMoreEnabled(true);
        binding.lrecyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page=1;
                initData();
            }
        });
        binding.lrecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page++;
                viewModel.getVideoTypeList(page, videoplaytype);
            }
        });
        binding.lrecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) { //滚动停止
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (layoutManager != null) {
                        int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                        int eddVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        if (eddVisibleItem == thisPosition) return;
                        thisPosition = eddVisibleItem;
                        int thisVideoView = eddVisibleItem - firstVisibleItem;
                        View itemView = layoutManager.getChildAt(thisVideoView);
                        if (itemView != null && thisPosition > 0 && thisPosition <= recommendAdapter.getDatas().size()) {
                            playCurVideo(itemView, thisPosition - 1);
                        }
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void setViewPagerLayoutManager() {
        viewPagerLayoutManager = new ViewPagerLayoutManager(getActivity());
        viewPagerLayoutManager.setCanVerticalScroll(true);
        binding.lrecyclerview.setLayoutManager(viewPagerLayoutManager);
        binding.lrecyclerview.smoothScrollToPosition(1);

    }


    private void updateVideo(int pos) {
        if (recommendAdapter.getDatas() != null && recommendAdapter.getDatas().size() > 0) {
            VideoListEntity.RecordsBean recordsBean = recommendAdapter.getDatas().get(pos);
            ItemViewHolder curHolder = recommendAdapter.getCurHolder(recordsBean.getVideoId());
            if (curHolder != null) {
                playCurVideo(curHolder.itemView, pos);
            }
        }
    }

    private void playCurVideo(View itemView, int pos) {
        VideoListEntity.RecordsBean recordsBean = recommendAdapter.getDatas().get(pos);
        //1.添加videoview到当前需要播放的item中,添加进item之前，保证ijkVideoView没有父view
        if (videoView == null) {
            videoView = new FullScreenVideoView2(itemView.getContext());
        }
        videoView.setVideoPath(recordsBean.getCoverURL());
        LikeView likeView = itemView.findViewById(R.id.likeviews);
        ViewGroup rootView = itemView.findViewById(R.id.video_layout);
        if (rootView == null) {
            return;
        }
        ViewGroup parent = (ViewGroup) videoView.getParent();
        if (parent != null) {
            if (mThumbImageBg != null) {
                mThumbImageBg.setVisibility(View.VISIBLE);
            }
            videoView.pauseCurrentVideo();
            parent.removeView(videoView);
        }
        rootView.addView(videoView, 0);
        //imageView.setVisibility(View.GONE);
        controllerView = itemView.findViewById(R.id.controllers);
        if (videoView == null || controllerView == null) {
            return;
        }
        likeView.setOnPlayPauseListener(new LikeView.OnPlayPauseListener() {
            @Override
            public void onPlayOrPause() {
                if (videoView == null) return;
                if (videoView.isPlaying()) {
                    videoView.pause();
                } else {
                    videoView.start();
                }
            }
        });
        //视频封面
        videoView.setVideoPath(recordsBean.getCoverURL());
        //评论点赞事件
        likeShareEvent(controllerView);
        //切换播放视频的作者主页数据
        if (bean != null && bean.size() > 0) {
            RxBus.getDefault().post(new UserBean(recordsBean.getCreateUser()));
        }
        videoView.start();
        viewModel.getplayVideo(recordsBean.getVideoId());
    }


    private void likeShareEvent(ControllerView controllerView) {
        controllerView.setListener(new OnVideoControllerListener() {
            //            点击头像的事件处理
            @Override
            public void onHeadClick(VideoListEntity.RecordsBean videoData) {
                if (videoData.getCreateUser().equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""))) {
                    getActivity().finish();
                } else {
                    videoView.pause();
                    ShareUserActivity.start(getActivity(), videoData.getCreateUser());
                }
            }

            //评论
            @Override
            public void onCommentClick(VideoListEntity.RecordsBean videoData) {
                new CommentDialog(getActivity(),videoData,"0",1,1).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        viewModel.getCommentNum(videoData,controllerView);
                    }
                });
            }

            @Override
            public void onTextureView(TextureView textureview) {

            }

            //点赞
            @Override
            public void onLikeClick(VideoListEntity.RecordsBean data) {
                viewModel.setLike(data.getVideoId() + "");
                setDianZan(data.getVideoId());
            }


            //            点击分享的事件处理
            @Override
            public void onShareClick(VideoListEntity.RecordsBean videoData) {
                new ShareDialog(getActivity(),1, videoData).setOnDeleteVideo(new ShareDialog.OnDeleteVideo() {
                    @Override
                    public void OnDeleteVideoData(int Id) {
                        DeleteVideo(Id);
                    }
                });
            }

            //         点击头像下面的+号事件处理
            @Override
            public void onFocusClick(VideoListEntity.RecordsBean videoData) {
                viewModel.getFens(videoData.getCreateUser());
                setGuanzhu(videoData.getVideoId());
            }

        });
    }

    //    删除视频的操作
    private void DeleteVideo(int id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("您的作品将被永久删除，无法找回。确认删除？");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除视频的操作逻辑
                roundCornerDialog.dismiss();
                viewModel.deleteMyVideo(id);
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    //删除完视频后重新加载视频数据
    public void setDataList() {
       *//* recommendAdapter.clearDatas();
        initData();*//*
       getActivity().finish();
    }

    //返回数据信息
    public void setVideoTypeList(List<VideoListEntity.RecordsBean> records) {
        if (null == records) {
            return;
        }
        for (VideoListEntity.RecordsBean at : records) {
            if (at.getIsLaud() == 0) {// 是否点赞（0：不是，1：是）
                at.setLiked(false);
            } else {
                at.setLiked(true);
            }
        }

        if (records.size() > 0) {
            recommendAdapter.addDatas(records);
        } else {
            MToast.showToast(getContext(), "没有视频啦");
        }
        this.bean =recommendAdapter.getDatas();
    }

    //    点赞
    public void setDianZan(String s) {
        for (VideoListEntity.RecordsBean bean : bean) {
            if (s.equals(bean.getVideoId())) {
                if (bean.isLiked()) {//为点赞
                    int laudCountq = bean.getLaudCount();
                    if (laudCountq != 0) {
                        laudCountq--;
                    }
                    bean.setLiked(false);
                    bean.setLaudCount(laudCountq);
                } else {
                    int laudCountd = bean.getLaudCount();
                    laudCountd++;
                    bean.setLaudCount(laudCountd);
                    bean.setLiked(true);
                }
                controllerView.like();
                controllerView.setVideoData(bean, getContext());
            }

        }
    }

    //关注
    private void setGuanzhu(String videoId) {
        for (VideoListEntity.RecordsBean bean : bean) {
            if (videoId.equals(bean.getVideoId())) {
                if (bean.getIsFollow() == 1) {//为关注
                    bean.setIsFollow(0);
                } else {//没有关注
                    bean.setIsFollow(1);
                }
                controllerView.setVideoData(bean, getContext());
            }

        }
    }

    private void setShuangJiDianZan(String videoId) {
        for (VideoListEntity.RecordsBean bean : bean) {
            if (videoId.equals(bean.getVideoId())) {
                if (bean.isLiked() == false) {
                    int laudCountd = bean.getLaudCount();
                    laudCountd++;
                    bean.setLaudCount(laudCountd);
                    bean.setLiked(true);
                }
                controllerView.like();
                controllerView.setVideoData(bean, getContext());
            }
        }
    }

    public void setCommentNum(VideoListEntity.RecordsBean videoData, ControllerView controllerView) {
        controllerView.setVideoData(videoData,getContext());
    }*/
}
